<template>
  <div class="board">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>订单信息</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <div class="bill-management-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-input
          v-model="pageData.searchText"
          placeholder="搜索账单ID、座位号或支付状态..."
          class="search-input"
          clearable
          @clear="handerSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handerSearch">
        <el-icon><Search /></el-icon>
        查询
      </el-button>
      <el-button type="success" @click="addDialogVisible = true">
        <el-icon><Plus /></el-icon>
        添加账单
      </el-button>
    </div>

    <!-- 账单表格 -->
    <el-table :data="pageData.records" stripe style="width: 100%" v-loading="loading":header-cell-style="{background: '#800000'}">
      <el-table-column prop="billId" label="账单ID" width="120" align="center" />
      <el-table-column label="用户" width="150" header-align="center" align="center">
        <template #default="scope">
          <span>{{ scope.row.userName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="电影" width="180" header-align="center" align="center">
        <template #default="scope">
          <span>{{ scope.row.movieName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="场次时间" width="180" header-align="center" align="center">
        <template #default="scope">
          <div>{{ scope.row.sessionDate }} {{ scope.row.playTime }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="seats" label="座位号" width="120" align="center" />
      <el-table-column label="支付状态" width="100" header-align="center" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.payState === 1 ? 'success' : 'danger'">
            {{ scope.row.payState === 1 ? '已支付' : '未支付' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="取消状态" width="100" header-align="center" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.cancelState === 1 ? 'danger' : 'success'">
            {{ scope.row.cancelState === 1 ? '已取消' : '未取消' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
      <el-table-column prop="deadline" label="截止时间" width="180" align="center" />
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="scope">
          <el-button size="small" type="primary"plain @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
              size="small"
              plain
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-section">
      <el-pagination
          v-model:current-page="pageData.current"
          v-model:page-size="pageData.size"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加账单对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加账单" width="500px">
      <el-form :model="addObj" label-width="100px">
        <el-form-item label="用户" prop="userId">
          <el-select
              v-model="addObj.userId"
              placeholder="请选择用户"
              style="width: 100%"
              @change="handleUserChange">
            <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="场次" prop="sessionId">
          <el-select
              v-model="addObj.sessionId"
              placeholder="请选择场次"
              style="width: 100%"
              @change="handleSessionChange">
            <el-option
                v-for="item in sessionOptions"
                :key="item.sessionId"
                :label="`${item.movieName} - ${item.hallName} - ${item.sessionDate} ${item.playTime}`"
                :value="item.sessionId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="座位" prop="seats">
          <el-select
              v-model="addObj.seats"
              multiple
              placeholder="请选择座位"
              style="width: 100%">
            <el-option
                v-for="seat in availableSeats"
                :key="seat"
                :label="seat"
                :value="seat">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="支付状态" prop="payState">
          <el-radio-group v-model="addObj.payState">
            <el-radio :label="1">已支付</el-radio>
            <el-radio :label="0">未支付</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="取消状态" prop="cancelState">
          <el-radio-group v-model="addObj.cancelState">
            <el-radio :label="1">已取消</el-radio>
            <el-radio :label="0">未取消</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handlerAddCancel">取消</el-button>
          <el-button type="primary" @click="handlerAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑账单对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑账单" width="600px">
      <el-form :model="editObj" label-width="100px">
        <el-form-item label="用户">
          <span>{{ editObj.userName }}</span>
        </el-form-item>

        <el-form-item label="场次">
          <span>{{ editObj.movieName }} - {{ editObj.hallName }} - {{ editObj.sessionDate }} {{ editObj.playTime }}</span>
        </el-form-item>

        <el-form-item label="座位" prop="seats">
          <el-select
              v-model="addObj.seats"
              multiple
              placeholder="请选择座位"
              style="width: 100%">
            <el-option
                v-for="seat in availableSeats"
                :key="seat"
                :label="seat"
                :value="seat">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="支付状态" prop="payState">
          <el-radio-group v-model="editObj.payState">
            <el-radio :label="1">已支付</el-radio>
            <el-radio :label="0">未支付</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="取消状态" prop="cancelState">
          <el-radio-group v-model="editObj.cancelState">
            <el-radio :label="1">已取消</el-radio>
            <el-radio :label="0">未取消</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handlerEditCancel">取消</el-button>
          <el-button type="primary" @click="handlerEditCommit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="删除账单" width="400px">
      <span>确定要删除该账单吗？此操作不可恢复！</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import api from '../api';
import lodash from 'lodash';
import { Search, Plus } from '@element-plus/icons-vue';

// 绑定表格数据
const pageData = ref({
  records: [],
  total: 0,
  size: 10,
  current: 1,
  pages: 1,
  searchText: ''
});

const loading = ref(false);
const deleteDialogVisible = ref(false);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);

const userOptions = ref([]);
const sessionOptions = ref([]);
const availableSeats = ref([]);



const deleteObj = ref({
  billId: '',
  index: -1
});

const addObj = ref({
  seats: '',
  payState: ''
});

const editObj = ref({
  billId: "",
  seats: '',
  payState: '',
  cancelState: '',
  createTime: '',
  deadline: '',
  cancelTime: ''
});

// 组件挂载后获取数据
onMounted(() => {
  getTableList();
  getUserOptions();
  getSessionOptions();
});


// 获取用户下拉选项
const getUserOptions = async () => {
  const result = await api.getUserList();
  userOptions.value = result;
}

// 获取场次下拉选项
const getSessionOptions = async () => {
  const result = await api.getSessionList();
  sessionOptions.value = result;
}

// 获取可用座位
const getAvailableSeats = async (sessionId) => {
  if (!sessionId) return;
  const result = await api.getAvailableSeats(sessionId);
  availableSeats.value = result;
}


// 获取表格数据
const getTableList = async () => {
  loading.value = true;
  try {
    const page = {
      current: pageData.value.current,
      size: pageData.value.size,
      searchText: pageData.value.searchText || ""
    };

    const result = await api.getBillPage(page);
    result.records.forEach(bill => {
      // 映射电影名称
      const user = userOptions.value.find(m => m.userId === bill.userId);
      bill.userName = user ? user.userName : '未知用户';

      // 映射影厅名称
      const session = sessionOptions.value.find(s => s.sessionId === bill.sessionId);
      if (session) {
        bill.movieName = session.movieName;
        bill.hallName = session.hallName;
        bill.playTime = session.playTime;
      } else {
        bill.movieName = '未知电影';
        bill.hallName = '未知影厅';
        bill.playTime = '未知时间';
      }

    });
    pageData.value = {
      ...result,
      searchText: page.searchText
    };
  } catch (error) {
    console.error("获取账单数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handerSearch = () => {
  pageData.value.current = 1;
  getTableList();
};

// 添加账单操作
const handlerAddCancel = () => {
  addObj.value = { seats: '', payState: '' };
  addDialogVisible.value = false;
};

const handlerAdd = async () => {
  try {
    await api.addBill(addObj.value);
    getTableList();
    addDialogVisible.value = false;
  } catch (error) {
    console.error("添加账单失败:", error);
  }
};

// 编辑账单操作
const handleEdit = (index, row) => {
  editDialogVisible.value = true;
  editObj.value = lodash.clone(row);
};

const handlerEditCancel = () => {
  editDialogVisible.value = false;
};

const handlerEditCommit = async () => {
  try {
    await api.editBill(editObj.value);
    getTableList();
    editDialogVisible.value = false;
  } catch (error) {
    console.error("更新账单失败:", error);
  }
};

// 删除账单操作
const handleDelete = (index, row) => {
  deleteObj.value.billId = row.billId;
  deleteObj.value.index = index;
  deleteDialogVisible.value = true;
};

const confirmDelete = async () => {
  try {
    await api.deleteBill(deleteObj.value.billId);
    pageData.value.records.splice(deleteObj.value.index, 1);
    getTableList();
    deleteDialogVisible.value = false;
  } catch (error) {
    console.error("删除账单失败:", error);
  }
};

// 分页控制
const handleSizeChange = (size) => {
  pageData.value.size = size;
  getTableList();
};

const handleCurrentChange = (current) => {
  pageData.value.current = current;
  getTableList();
};
</script>

<style scoped>
.bill-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table {
  margin-top: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  overflow: hidden;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
